package com.zw.yzk.kabu.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.adapter.ConfirmGoodsOrderShopAdapter;
import com.zw.yzk.kabu.base.BaseActivity;
import com.zw.yzk.kabu.constant.ActivityConstant;
import com.zw.yzk.kabu.data.cache.db.DataBaseManager;
import com.zw.yzk.kabu.data.cache.db.ShoppingAddress;
import com.zw.yzk.kabu.data.cache.db.ShoppingAddressDao;
import com.zw.yzk.kabu.data.cache.db.User;
import com.zw.yzk.kabu.internal.component.DaggerConfirmGoodsOrderComponent;
import com.zw.yzk.kabu.internal.module.ActivityModule;
import com.zw.yzk.kabu.internal.module.SubmitGoodsOrderModule;
import com.zw.yzk.kabu.management.LoadingDialogManager;
import com.zw.yzk.kabu.management.ToastManager;
import com.zw.yzk.kabu.management.ToolbarBuilder;
import com.zw.yzk.kabu.model.SubmitGoods;
import com.zw.yzk.kabu.model.SubmitOrder;
import com.zw.yzk.kabu.presenter.ConfirmGoodsOrderPresenter;
import com.zw.yzk.kabu.utils.CalculateUtils;
import com.zw.yzk.kabu.utils.ResUtils;
import com.zw.yzk.kabu.view.view.ConfirmGoodsOrderView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by zhanwei on 2017/2/5.
 */

public class ConfirmGoodsOrderActivity extends BaseActivity implements ConfirmGoodsOrderView {

    @Bind(R.id.name)
    TextView name;
    @Bind(R.id.phone)
    TextView phone;
    @Bind(R.id.address)
    TextView address;
    @Bind(R.id.total_price)
    TextView totalPrice;
    @Bind(R.id.order_list)
    RecyclerView orderList;
    @Bind(R.id.layout_address_info)
    View addressInfo;
    @Bind(R.id.add_address)
    View addAddress;

    @Inject
    ConfirmGoodsOrderPresenter presenter;
    private ConfirmGoodsOrderShopAdapter adapter;

    @Override
    public int getLayoutId() {
        return R.layout.activity_confirm_goods_order;
    }

    @Override
    public void iniToolbar(BaseActivity activity) {
        ToolbarBuilder
                .createBuilder(this)
                .setTitle(getResources().getString(R.string.confirm_goods_order))
                .build();
    }

    @Override
    public void initComponent() {
        DaggerConfirmGoodsOrderComponent.builder()
                .applicationComponent(getApplicationComponent())
                .activityModule(new ActivityModule(this))
                .submitGoodsOrderModule(new SubmitGoodsOrderModule())
                .build()
                .inject(this);
        presenter.setView(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setReceiverInfo();
        initRecyclerView();
        List<SubmitOrder> orderList = getIntent().getParcelableArrayListExtra(ActivityConstant.CONFIRM_GOODS_ORDER_LIST);
        refreshOrderList(dealOrderList(orderList));
    }

    @Override
    protected void onResume() {
        super.onResume();
        User user = DataBaseManager.getInstance().getLoginUser();
        ShoppingAddress address;
        try {
            address = DataBaseManager.getInstance()
                    .getShoppingAddressDao().queryBuilder()
                    .where(ShoppingAddressDao.Properties.Id.eq(DataBaseManager.getInstance().getLoginUser().getAddressId()))
                    .build()
                    .unique();
        } catch (Exception e) {
            address = null;
            e.printStackTrace();
        }
        if (user == null || user.getAddress() == null || address == null) {
            addressInfo.setVisibility(View.INVISIBLE);
            addressInfo.setEnabled(false);
            addAddress.setVisibility(View.VISIBLE);
        } else {
            if (!adapter.getOrderList().isEmpty()) {
                for (SubmitOrder order : adapter.getOrderList()) {
                    order.setReceiverInfoId(address.getReceiveId());
                }
            }
        }
        checkTradeStatus();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.destroy();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        switch (requestCode) {
            case ActivityConstant.SELECT_ADDRESS:
                String name = data.getStringExtra(ActivityConstant.SELECTED_RECEIVER_NAME);
                String phone = data.getStringExtra(ActivityConstant.SELECTED_RECEIVER_PHONE);
                String address = data.getStringExtra(ActivityConstant.SELECTED_RECEIVER_ADDRESS);
                initReceiverInfo(name, phone, address);
                break;
            default:
                break;
        }
    }

    @Override
    public void queryOrderStateSuccess() {

    }

    @OnClick(R.id.confirm_order)
    public void confirmOrder() {
        setSubmitOrder();
        LoadingDialogManager.getInstance().showLoadingDialog(this);
    }

    @OnClick(R.id.add_address)
    public void addAddress() {
        Intent intent = new Intent(this, ShippingAddressActivity.class);
        intent.putExtra(ActivityConstant.SELECT_ADDRESS_ENABLE, true);
        startActivityForResult(intent, ActivityConstant.SELECT_ADDRESS);
    }

    @OnClick(R.id.layout_address_info)
    public void selectAddress() {
        Intent intent = new Intent(this, ShippingAddressActivity.class);
        intent.putExtra(ActivityConstant.SELECT_ADDRESS_ENABLE, true);
        startActivityForResult(intent, ActivityConstant.SELECT_ADDRESS);
    }

    /**
     * 初始化订单列表
     */
    private void initRecyclerView() {
        orderList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        orderList.setNestedScrollingEnabled(false);
    }

    /**
     * 设置收货人信息
     */
    private void setReceiverInfo() {
        User user = DataBaseManager.getInstance().getLoginUser();
        if (user == null || user.getAddress() == null) {
            addressInfo.setVisibility(View.INVISIBLE);
            addressInfo.setEnabled(false);
            addAddress.setVisibility(View.VISIBLE);
            return;
        }
        initReceiverInfo(user.getAddress().getReceiverName(),
                user.getAddress().getReceiverPhone(), user.getAddress().getAddress());
    }

    /**
     * 更新收货人信息
     *
     * @param n 名称
     * @param p 电话
     * @param a 地址
     */
    private void initReceiverInfo(String n, String p, String a) {
        addAddress.setVisibility(View.GONE);
        addressInfo.setVisibility(View.VISIBLE);
        addressInfo.setEnabled(true);

        name.setText(n);
        phone.setText(p);
        address.setText(a);
    }

    /**
     * 刷新订单列表
     *
     * @param list 订单列表
     */
    private void refreshOrderList(List<SubmitOrder> list) {
        if (adapter == null) {
            adapter = new ConfirmGoodsOrderShopAdapter(list);
            orderList.setAdapter(adapter);
        } else {
            adapter.refresh(list);
        }
    }

    /**
     * 处理订单列表，增加商品总数和商品总额
     *
     * @param list 订单列表
     */
    private List<SubmitOrder> dealOrderList(List<SubmitOrder> list) {
        if (list == null || list.isEmpty()) {
            return new ArrayList<>();
        }
        BigDecimal total = new BigDecimal(0f);
        for (SubmitOrder order : list) {
            if (order.getGoodsList() == null) {
                continue;
            }
            BigDecimal shopPrice = new BigDecimal(0f);
            int totalCount = 0;
            float shopHighestFreight = 0f;
            for (SubmitGoods goods : order.getGoodsList()) {
                shopPrice = shopPrice.add(new BigDecimal(goods.getPrice()).multiply(new BigDecimal(goods.getCount())));
                totalCount += goods.getCount();
                if(shopHighestFreight < goods.getFreight()) {
                    shopHighestFreight = goods.getFreight();
                }
            }
            total = total.add(shopPrice).add(new BigDecimal(shopHighestFreight));
            order.setShopFreight(shopHighestFreight);
            order.setShopGoodsCount(totalCount);
            order.setGoodsPrice(CalculateUtils.setScale(shopPrice, 2));
        }

        //设置订单总额
        totalPrice.setText(ResUtils.formatCurrency(this, total.floatValue()));
        return list;
    }

    /**
     * 提交订单
     */
    public void setSubmitOrder() {
        if (adapter == null) {
            return;
        }
        presenter.setSubmitOrder(adapter.getOrderList());
    }

    /**
     * 查询订单状态
     */
    public void checkTradeStatus() {
        presenter.checkOrderState();
    }

}
